using Cysharp.Threading.Tasks;
using Game;
using UnityEngine;

public sealed class ShipGun : MonoBehaviour {
	public float EnergyPerShoot = 50;
	public float ShootInterval = 0.2f;
	public float MaxDistance = 10f;
	public int Damage = 10;
	public LineRenderer ShootLine;

	float    _lastShootTime;
	ShipCore _owner;
	AudioSource _audio;

	private void Awake() {
		_owner = GetComponentInParent<ShipCore>();
		ShootLine.enabled = false;
		_audio = GetComponent<AudioSource>();
	}

	public bool CanShoot() {
		if ( Time.time - _lastShootTime < ShootInterval ) {
			return false;
		}
		if ( _owner.Reactor.HasEnergy(EnergyPerShoot) ) {
			return true;
		}
		return false;
	}

	public bool Shoot() {
		if ( !CanShoot() ) {
			return false;
		}
		_ = ShootEffect();
		_lastShootTime= Time.time;

		if ( !_owner || !GameManager.Instance.IsServer ) {
			return true;
		}
		_owner.Reactor.UseEnergy(EnergyPerShoot);

		if (!Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out var hit, MaxDistance, CommonStaticData.Instance.AllCollisionsMask, QueryTriggerInteraction.Ignore)) {
			return true;
		}
		var receiver = hit.collider.GetComponent<IDamageReceiver>();
		if ( receiver != null ) {
			receiver.ApplyDamage(new DamageDescription(_owner.ID, _owner.Team, Damage, hit.point, hit.normal));
		}
		return true;
	}

	async UniTask ShootEffect() {
		ShootLine.enabled = true;
		_audio?.Play();
		await UniTask.Delay(100);
		if ( ShootLine ) {
			ShootLine.enabled = false;
		}		
	}
}
